import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
  Input,
  Button,
  Table,
  message,
  Modal,
  Tree,
  Tag,
  Select,
  InputNumber,
  TreeSelect,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  DownOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import { text_check, post_axios, key_find_obj } from "../../utils";

export default function BrandPolicy(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const [treeHeight, setTreeHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const { confirm } = Modal;
  // 国内国外判断
  const session_company = sessionStorage.getItem("company");

  const [organization_list, setOrganization_list] = useState([]);
  const [expanded_array, setExpandedArray] = useState([]);
  const getData = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    setSpinning(true);
    let res = await post_axios("admin_oneself", "m_query_all", upMsg);
    setSpinning(false);
    if (!res) return;
    let rows = res.data_rows.rows;
    let expanded_array = rows[0].child.map((item) => {
      return item.org_id;
    });
    setOrganization_list(rows);
    setExpandedArray(expanded_array);
  };

  // 组织列表点击
  const [clicked_comId, setClicked_comId] = useState("");
  const [clicked_comObj, setClicked_comObj] = useState({});
  const organization_row_click = (row) => {
    console.log(row);
    setClicked_comId(row.org_id);
    setClicked_comObj(row);
    get_organization_brand_data(page, rows, row);
  };

  const [data_list, setData_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);

  const get_organization_brand_data = async (newPage, newRows, item) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      org_id: item ? item.org_id : "",
    };
    setSpinning(true);
    let res = await post_axios("brand_policy", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setData_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("system_manager.number"),
      dataIndex: "brand_number",
      align: "center",
    },
    {
      title: t("system_manager.name"),
      dataIndex: "brand_name",
      align: "center",
    },
    {
      title: t("system_manager.company"),
      dataIndex: "company",
      align: "center",
    },
  ];

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.id);
    setclickRow(row);
  };

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    initData();
  };

  const initData = () => {
    setClickRowKey("");
    setclickRow([]);
    getData();
  };

  const delete_brand = async () => {
    if (clickRowKey === "") {
      message.warning({
        content: "请选择一个品牌策略",
      });
      return;
    }
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: clickRowKey,
    };
    let res = await post_axios("brand_policy", "m_del", upMsg);
    if (!res) return;
    message.success({
      content: t("common.delete_success"),
    });
    search_data();
  };

  const [edit_brand_show, setEdit_brand_show] = useState(false);
  const [edit_bank_com_id, setEdit_bank_com_id] = useState("");
  const [edit_bank_com_name, setEdit_bank_com_name] = useState("");
  const [edit_bank_com_grade, setEdit_bank_com_grade] = useState("");
  const [edit_brand_number, setEdit_brand_number] = useState("");
  const [edit_max_qty, setEdit_max_qty] = useState(0);
  const [edit_description, setEdit_description] = useState("");
  const add_dialog_show = () => {
    setEdit_bank_com_id("");
    setEdit_bank_com_name("");
    setEdit_bank_com_grade("");
    setEdit_brand_number("");
    setEdit_max_qty(0);
    setEdit_description("");
    setEdit_brand_show(true);
  };

  const orgOnChange = (value, label, extra) => {
    console.log(value, label, extra);
    setEdit_bank_com_id(value);
    setEdit_bank_com_name(label);
  };

  const edit_brand_confirm = async () => {
    if (edit_bank_com_id === "") {
      message({
        content: "请选择组织",
      });
      return;
    }
    if (edit_brand_number === "") {
      message({
        content: "请选择品牌",
      });
      return;
    }
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      org_id: edit_bank_com_id,
      org_grade: edit_bank_com_id.split("_").length,
      org_name: edit_bank_com_name[0],
      brand_name: key_find_obj(edit_brand_number, brand_list, "brand_number")
        .brand_name,
      brand_number: edit_brand_number,
      max_qty: edit_max_qty,
      description: edit_description,
    };
    let res = await post_axios("brand_policy", "m_add", upMsg);
    if (!res) return;
    setEdit_brand_show(false);
    search_data();
  };

  const [brand_list, setBrand_list] = useState([]);
  const get_brand_list = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("brand", "m_query", upMsg);
    if (!res) return;
    setBrand_list(res.data_rows.rows);
  };

  function gradeItem(nodeData) {
    switch (nodeData.org_grade) {
      case "1":
        return <Tag color="#2db7f5">{t("system_manager.level1")}</Tag>;
      case "2":
        return <Tag color="#2db7f5">{t("system_manager.level2")}</Tag>;
      case "3":
        return <Tag color="#2db7f5">{t("system_manager.level3")}</Tag>;
      case "4":
        return <Tag color="#2db7f5">{t("system_manager.level4")}</Tag>;
      case "5":
        return <Tag color="#2db7f5">商户</Tag>;
      case "6":
        return <Tag color="#2db7f5">项目</Tag>;
      case "7":
        return <Tag color="#2db7f5">点位</Tag>;
      default:
        return "";
    }
  }
  useEffect(() => {
    // 挂载后或者更新后的操作
    if (user_grade < 70) {
      getData().then(() => {
        const tabBoxHeight =
          document.getElementsByClassName("brand_policy")[0].scrollHeight;
        const tableHeight = tabBoxHeight - 96 - 30;
        const treeHeight = tabBoxHeight - 42 - 30;
        setTableHeight(tableHeight);
        setTreeHeight(treeHeight);
      });
    } else {
      get_organization_brand_data().then(() => {
        const tabBoxHeight =
          document.getElementsByClassName("brand_policy")[0].scrollHeight;
        const tableHeight = tabBoxHeight - 96 - 30;
        const treeHeight = tabBoxHeight - 42 - 30;
        setTableHeight(tableHeight);
        setTreeHeight(treeHeight);
      });
    }
    get_brand_list();
  }, []);
  return (
    <>
      <div className="brand_policy modules">
        <div className="table_box">
          <div className="tree_box">
            {user_grade < 70 ? (
              treeHeight !== 0 ? (
                <Tree
                  showLine
                  switcherIcon={<DownOutlined />}
                  defaultExpandedKeys={expanded_array}
                  treeData={organization_list}
                  height={treeHeight}
                  fieldNames={{
                    title: "org_name",
                    key: "org_id",
                    children: "child",
                  }}
                  blockNode
                  titleRender={(nodeData) => {
                    return (
                      <p key={nodeData.org_id}>
                        <span style={{ marginRight: "10px" }}>
                          {nodeData.org_name}
                        </span>
                        {gradeItem(nodeData)}
                      </p>
                    );
                  }}
                  onSelect={(_, e) => {
                    const { node } = e;
                    return organization_row_click(node);
                  }}
                />
              ) : (
                ""
              )
            ) : (
              <div className="loading_modules">模块加载中...</div>
            )}
          </div>
          <div
            style={{
              width: user_grade < 70 ? "70vw" : "100vw",
            }}
          >
            <div className="screen_btn">
              <div className="btn_box">
                {/* 添加 */}
                {menu_action.indexOf("m_add") > -1 ? (
                  <Button
                    size="small"
                    type="text"
                    icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                    onClick={add_dialog_show}
                  >
                    {text_check(user_power_lang["m_add"])}
                  </Button>
                ) : (
                  ""
                )}
                {/* 修改 */}
                {menu_action.indexOf("m_modify") > -1 ? (
                  <Button
                    size="small"
                    type="text"
                    icon={<EditOutlined style={{ color: "#1677FF" }} />}
                  >
                    {text_check(user_power_lang["m_modify"])}
                  </Button>
                ) : (
                  ""
                )}
                {/* 删除 */}
                {menu_action.indexOf("m_del") > -1 ? (
                  <Button
                    size="small"
                    type="text"
                    icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                    onClick={delete_brand}
                  >
                    {text_check(user_power_lang["m_del"])}
                  </Button>
                ) : (
                  ""
                )}
                {/* 查询 */}
                {menu_action.indexOf("m_query") > -1 ? (
                  <Button
                    size="small"
                    type="text"
                    icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                    onClick={search_data}
                  >
                    {text_check(user_power_lang["m_query"])}
                  </Button>
                ) : (
                  ""
                )}
              </div>
            </div>
            <div className="page-table">
              <Table
                dataSource={data_list}
                size="small"
                bordered
                columns={columns}
                rowKey="id"
                virtual
                scroll={{
                  y: tableHeight,
                }}
                rowHoverable={false}
                onRow={(record) => {
                  return {
                    onClick: () => tableRowClick(record), // 点击行
                  };
                }}
                rowClassName={(record, index) => {
                  if (record.id == clickRowKey) {
                    return "row_clicked_style";
                  }
                }}
                pagination={{
                  defaultCurrent: page,
                  defaultPageSize: rows,
                  size: "small",
                  current: page,
                  total: total,
                  responsive: true,
                  showTotal: (total) =>
                    text_check({
                      msg_cn: `共 ${total} 条`,
                      msg_en: `Total ${total} items`,
                    }),
                  onChange: pageOnChange,
                }}
              />
            </div>
          </div>
        </div>
      </div>

      <Modal
        title="新增品牌"
        open={edit_brand_show}
        onOk={edit_brand_confirm}
        onCancel={() => setEdit_brand_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">品牌</div>
          <Select
            placeholder=" "
            value={edit_brand_number}
            onChange={(value) => setEdit_brand_number(value)}
            options={brand_list}
            fieldNames={{
              label: "brand_name",
              value: "brand_number",
            }}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">{t("market.organization")}</div>
          <TreeSelect
            treeData={organization_list}
            fieldNames={{
              label: "org_name",
              value: "org_id",
              children: "child",
            }}
            placeholder=" "
            value={edit_bank_com_id}
            onChange={orgOnChange}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">上限</div>
          <InputNumber
            placeholder=" "
            min={0}
            max={255}
            value={edit_max_qty}
            onChange={(value) => setEdit_max_qty(value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">备注</div>
          <Input
            placeholder=" "
            value={edit_description}
            onChange={(e) => setEdit_description(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
